package com.whc;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 滑动窗口---限流算法
 * Created by Administrator on 2022/2/17.
 */
public class RateLimerTime {

    private Map<String, List<Long>> map = new ConcurrentHashMap<String, List<Long>>();

    public boolean isGo(String card, long timeWindow, int count) {
        long nowTime = System.currentTimeMillis();
        if (!map.containsKey(card)) {
            map.put(card, new LinkedList<Long>());
        }
        List<Long> list = map.get(card);
        if (list.size() < count) {
            list.add(0, nowTime);
            return true;
        }

        Long lastTime = list.get(count - 1);
        if (lastTime < timeWindow) {
            return false;
        } else {
            list.remove(count - 1);
            list.add(0, nowTime);
            return true;
        }
    }
}
